package com.yksj.healthtalk.ui.login;

import java.io.File;
import java.io.FileOutputStream;

import org.universalimageloader.core.assist.ImageScaleType;
import org.universalimageloader.core.assist.ImageSize;
import org.universalimageloader.core.assist.ViewScaleType;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.BinaryHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.MainTabUI;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.doctorstation.DoctorHomeMainActivity;
import com.yksj.healthtalk.utils.BitmapUtils;
import com.yksj.healthtalk.utils.DataParseUtil;
import com.yksj.healthtalk.utils.FileUtils;
import com.yksj.healthtalk.utils.SharePreUtils;

public class WelcomeActivity extends BaseFragmentActivity {
	
	ImageView mImageView;
	Bitmap mBitmap;
	
	final Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			boolean b = SharePreUtils.getLoginState();//是否已经登录
			if(b){
				onHandleCrashedLogin();
			}else{
				onHandleLogin();
			}
			finish();
		};
	};
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.logo_layout);
		CoreService.actionStart(this);
		mImageView = (ImageView)findViewById(R.id.logo_imgv);
//		FrameLayout frame=(FrameLayout) findViewById(R.id.frame);

		/*Animation animation = AnimationUtils.loadAnimation(this,R.anim.logo_anim);
		animation.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
			}
			@Override
			public void onAnimationEnd(Animation animation) {
				animation.setAnimationListener(null);
				handler.sendEmptyMessage(1);
				if(mBitmap != null){
					mImageView.clearAnimation();
					mImageView.setBackgroundDrawable(new BitmapDrawable(mBitmap));
					handler.sendEmptyMessageDelayed(1, 3000);
				}else{
					handler.sendEmptyMessage(1);
				}
			}
		});*/
		//new ImageDowLoad().execute();
		handler.sendEmptyMessageDelayed(1, 2000);
//		mImageView.startAnimation(animation);
	}
	
	private void onHandleLogin(){
		Intent intent = new Intent(WelcomeActivity.this,UserLoginUI.class);
		startActivity(intent);
		//overridePendingTransition(0,0);
		//finish();
	}
	
	/**
	 * 异常退出登录处理
	 */
	private void onHandleCrashedLogin(){
		try{
			String parame = SharePreUtils.getLoginUserInfo();
			String[] str = SharePreUtils.fatchUserLoginCache();
			JSONObject jsonObject = JSON.parseObject(parame);
			CustomerInfoEntity entity = DataParseUtil.jsonToCustomerInfo(jsonObject);
			SmartControlClient controlClient = SmartControlClient.getControlClient();
			controlClient.setUserPassword(str[0],str[1]);
			controlClient.setCustomerInfoEntity(entity);
			
			Intent intent;
			if(SharePreUtils.fatchLockState()){
				intent = new Intent(WelcomeActivity.this,DoctorHomeMainActivity.class);
			}else{
				intent = new Intent(WelcomeActivity.this,MainTabUI.class);
			}
			startActivity(intent);
			finish();
			CoreService.actionLogin(this);
		}catch(Exception e){
			SharePreUtils.updateLoginState(false);
			onHandleLogin();
		}
	}
	
	public ImageSize getImageSize(){
		WindowManager vm  = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
		int width = vm.getDefaultDisplay().getWidth();
		int height = vm.getDefaultDisplay().getHeight();
		Rect rect = new Rect();
		getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
		ImageSize size = new ImageSize(width,height-rect.top);
		return size;
	}
	
	class ImageDowLoad extends AsyncTask<Void, Void, Bitmap>{
		@Override
		protected Bitmap doInBackground(Void... params) {
			String picture="";
			final File file = new File(getCacheDir(),"welcome_bg_huan");
			ImageSize targetSize = getImageSize();
			try{
				Bitmap  mBitmap = BitmapUtils.decode(file,targetSize, ImageScaleType.EXACTLY,ViewScaleType.FIT_INSIDE);
				return mBitmap;
			}catch(Exception e){
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Bitmap result) {
			mBitmap = result;
			String picture="";
			final File file = new File(getCacheDir(),"welcome_bg_huan");
			HttpRestClient.dowloadProgressImage(new BinaryHttpResponseHandler(){
				@Override
				public void onSuccess(int statusCode, byte[] binaryData) {
					super.onSuccess(statusCode, binaryData);
					if(binaryData != null || binaryData.length >0){
						file.delete();
					}
					FileOutputStream outputStream = null;
					try {
						outputStream = new FileOutputStream(file);
						outputStream.write(binaryData);
						outputStream.flush();
					} catch (Exception e) {
						e.printStackTrace();
					}finally{
						FileUtils.close(outputStream);
					}
				}
			});
		}
	}
	
}
